package partParsers;

import java.io.IOException;

//this class extracts data from main advertisment table of real estate html
public class MainTableParser extends IndexesFinder implements PartParser {
	protected String[][] data=null;//html main table data
								   //A[i][j] data with index indexs[i] and
								   //type titlesType[j].			
	protected int colNum;//number of columns in table
	
	//Constructor
	public MainTableParser(
		String buf,
		String idToken,
		String tablePrefix,
		int indexes[],
		int colNum)
	{
		super(buf,idToken,tablePrefix);
		this.indexes=indexes;
		this.colNum=colNum;
	}
	
	//returns type of i'th row and j'th column in main advertisment's table
	public String getData(int i,int j){return data[i][j];};		
	
	//Method search for advertisments column names string
	//Initializes 'mainData' attribute. 
	//!!!Assumes that 'buffer' and 'indexes' already initialized.
	public boolean parse() throws IOException 
	{
		data=new String[indexes.length][];
		int startPos,endPos=0,j=0,pos,prefixPos;
		String sFound;//last data string found
		
		//look for prefix of advertisment table
		prefixPos=txtFinder.indexOf(tablePrefix);
		if(prefixPos<0)
			prefixPos=0;		
		
		//look for advertisments main data
		for(int i=0;i<indexes.length;i++)
		{
			data[i]=new String[colNum];
			startPos=txtFinder.indexOf(idToken+String.valueOf(indexes[i]),prefixPos);
			endPos=txtFinder.indexOf("</TR>",startPos);
			txtFinder.moveTo(startPos);
			j=0;
			pos=txtFinder.indexOf("</TD>",startPos);
			if(pos<0)
				pos=endPos;
			while(txtFinder.hasNext() && j<colNum && txtFinder.getPos()<endPos)
			{				
				sFound=
					txtFinder.getHtmlText(
						txtFinder.indexOf(">", txtFinder.getPos())+1);
				
				if(sFound!=null)
				{
					while(pos<txtFinder.getPos() && pos<endPos)
					{
						pos=txtFinder.indexOf("</TD>",pos+1);
						if(pos<0)
							pos=endPos+1;
						j++;
					}
					if(j<colNum)
						data[i][j]=sFound;
					//j++;
				}
				
			}
			txtFinder.moveTo(
				txtFinder.indexOf(
					idToken+String.valueOf(indexes[i]),
					txtFinder.getPos()));
		}
		txtFinder.moveTo(0);
		return true;
	}

	public Object[] toArray() {
		return data.clone();
	}

}
